// pages/profile-list/profile-list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    profileList: [],
    showModal: false,
    editingId: null,
    formData: {
      name: '',
      gender: '男',
      birthDate: '',
      relation: '本人',
      birthPlace: ''
    },
    genderList: ['男', '女'],
    relationList: ['本人', '父亲', '母亲', '儿子', '女儿', '丈夫', '妻子', '兄弟', '姐妹', '祖父', '祖母', '外祖父', '外祖母'],
    genderIndex: 0,
    relationIndex: 0,
    regionArray: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadProfileList();
    // 如果有autoAdd参数，自动打开添加档案弹窗
    if (options.autoAdd === 'true') {
      setTimeout(() => {
        this.showAddModal();
      }, 100);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadProfileList();
  },

  // 加载档案列表
  loadProfileList() {
    const profileList = wx.getStorageSync('profiles') || [];
    this.setData({
      profileList: profileList
    });
  },

  // 显示添加弹框
  showAddModal() {
    const today = new Date();
    const dateStr = today.getFullYear() + '-' + 
                   String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                   String(today.getDate()).padStart(2, '0');
    
    this.setData({
      showModal: true,
      editingId: null,
      formData: {
        name: '',
        gender: '男',
        birthDate: dateStr,
        relation: '本人',
        birthPlace: ''
      },
      genderIndex: 0,
      relationIndex: 0,
      regionArray: []
    });
  },

  // 隐藏添加弹框
  hideAddModal() {
    this.setData({
      showModal: false,
      editingId: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 查看档案详情
  viewProfile(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/profile-detail/profile-detail?id=${id}`
    });
  },

  // 编辑档案
  editProfile(e) {
    const id = e.currentTarget.dataset.id;
    const profileList = wx.getStorageSync('profiles') || [];
    const profile = profileList.find(item => item.id == id);
    
    if (profile) {
      // 设置编辑模式的表单数据
      const genderIndex = this.data.genderList.indexOf(profile.gender);
      const relationIndex = this.data.relationList.indexOf(profile.relation);
      
      this.setData({
        showModal: true,
        editingId: id,
        formData: {
          name: profile.name,
          gender: profile.gender,
          birthDate: profile.birthDate,
          relation: profile.relation,
          birthPlace: profile.birthPlace || ''
        },
        genderIndex: genderIndex >= 0 ? genderIndex : 0,
        relationIndex: relationIndex >= 0 ? relationIndex : 0,
        regionArray: profile.birthPlace ? profile.birthPlace.split(' ') : []
      });
    }
  },

  // 表单输入处理
  onNameInput(e) {
    this.setData({
      'formData.name': e.detail.value
    });
  },

  onGenderChange(e) {
    const index = e.detail.value;
    this.setData({
      genderIndex: index,
      'formData.gender': this.data.genderList[index]
    });
  },

  onBirthDateChange(e) {
    this.setData({
      'formData.birthDate': e.detail.value
    });
  },

  onRelationChange(e) {
    const index = e.detail.value;
    this.setData({
      relationIndex: index,
      'formData.relation': this.data.relationList[index]
    });
  },

  onRegionChange(e) {
    const regionArray = e.detail.value;
    const birthPlace = regionArray.join('');
    this.setData({
      regionArray: regionArray,
      'formData.birthPlace': birthPlace
    });
  },

  // 保存档案
  saveProfile() {
    const { name, gender, birthDate, relation, birthPlace } = this.data.formData;
    
    // 表单验证
    if (!name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return;
    }
    
    if (!birthDate) {
      wx.showToast({
        title: '请选择出生时间',
        icon: 'none'
      });
      return;
    }
    
    if (!relation) {
      wx.showToast({
        title: '请选择与我的关系',
        icon: 'none'
      });
      return;
    }
    
    // 创建档案对象
    const profile = {
      id: Date.now(),
      name: name.trim(),
      gender,
      birthDate,
      relation,
      birthPlace: birthPlace || '',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
    
    // 获取现有档案列表
    let profiles = wx.getStorageSync('profiles') || [];
    
    if (this.data.editingId) {
      // 编辑模式：更新现有档案
      const index = profiles.findIndex(item => item.id == this.data.editingId);
      if (index >= 0) {
        profile.id = this.data.editingId;
        profile.createTime = profiles[index].createTime; // 保持原创建时间
        profiles[index] = profile;
      }
    } else {
      // 新增模式：添加新档案
      profiles.push(profile);
    }
    
    // 保存到本地存储
    wx.setStorageSync('profiles', profiles);
    
    // 隐藏弹框并重新加载数据
    this.setData({
      showModal: false,
      editingId: null
    });
    
    // 重新加载档案列表
    this.loadProfileList();
    
    wx.showToast({
      title: this.data.editingId ? '更新成功' : '添加成功',
      icon: 'success'
    });
  },

  // 删除档案
  deleteProfile(e) {
    const id = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个档案吗？',
      success(res) {
        if (res.confirm) {
          let profileList = wx.getStorageSync('profiles') || [];
          profileList = profileList.filter(item => item.id !== id);
          wx.setStorageSync('profiles', profileList);
          that.loadProfileList();
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})